package com.crazymaker.springcloud.websocket.service.impl;

import com.crazymaker.springcloud.common.util.ThreadUtil;
import com.crazymaker.springcloud.distribute.zookeeper.ZKClient;
import com.crazymaker.springcloud.standard.context.SpringContextUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Component;

import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.concurrent.TimeUnit;

import static com.crazymaker.push.platform.contract.constants.PushConstants.WEBSOCKET_SERVER_MONITOR_PATH;

/**
 *
 */
@Slf4j
@Component
public class Regist2WebSocketGateWay implements ApplicationContextAware {


    @Value("${websocket.register.gateway}")
    private String websocketRegisterGateway;
    private String pathRegistered;


    public String doRegist2WebSocketGateWay() {
        InetAddress addr = null;
        try {
            addr = InetAddress.getLocalHost();
        } catch (UnknownHostException e) {
            e.printStackTrace();
            return null;
        }

        String host = addr.getHostAddress();
        Environment env = SpringContextUtil.getApplicationContext().getEnvironment();
        String port = env.getProperty("tunnel.websocket.port");

        String subPath = host + ":" + port;

        String parentPath = WEBSOCKET_SERVER_MONITOR_PATH;
        pathRegistered = ZKClient.getSingleton().createEphemeralNode(parentPath, subPath);
        log.info("pathRegistered is : {}", pathRegistered);
        return pathRegistered;
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        SpringContextUtil.setContext(applicationContext);

        delayRegist();
    }

    private void delayRegist() {
        ThreadUtil.delayRun(() -> {

            if (ZKClient.getSingleton().isReady()) {
                doRegist2WebSocketGateWay();
            } else {
                //如果zk没有连接成功，这块做递归
                delayRegist();
            }
        }, ZKClient.DEPEND_DELAY, TimeUnit.SECONDS);
    }

}
